package com.zhouchb.blog.Controller;

import com.zhouchb.blog.bean.Blog;
import com.zhouchb.blog.bean.Comment;
import com.zhouchb.blog.bean.User;
import com.zhouchb.blog.service.BlogService;
import com.zhouchb.blog.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.ConcurrentModificationException;
import java.util.List;

/**
 * @Author Zhouchb
 * @Create 2021-09-2021/9/12 :21:37
 * @Description
 */
@Slf4j
@Controller
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private BlogService blogService;
    @Value("${comment.avatar}")
    private String avatar;
    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable("blogId")Long blogId, Model model){
        List<Comment> comments = commentService.listCommentByBlogIdService(blogId);
        model.addAttribute("comments",comments);
        return "blog :: commentList";
    }
    @PostMapping("/comments")
    public String post(Comment comment, HttpSession session){
        Long blogId = comment.getBlogId();
        Blog blog = blogService.getBlogByIdService(blogId);
        comment.setBlog(blog);
        User user = (User) session.getAttribute("user");
        if (user != null){
            comment.setAdminComment(true);
            comment.setAvatar(user.getAvatar());
            comment.setNickname(user.getNickname());
        }else {
            comment.setAvatar(avatar);
        }
        System.out.println(comment.getParentComment());
        commentService.saveCommentService(comment);
        return "redirect:/comments/"+ blogId;
    }
}
